import CryptoJS from 'crypto-js';
export function encode(
  id,
  config = {
    CREATION_DATE: 260224,
    AES_KEY: '6433432C713528557A25715E78573950353437583F675372',
    PRODUCT_CODE: '44454C454F2D00010001000001(create_date)3F882',
  }
) {
  const uid = stringToByteArray(id);
  const CREATION_DATE = Number(config.CREATION_DATE).toString(16).toUpperCase();
  const PRODUCT_CODE = config.PRODUCT_CODE.replace('(create_date)', CREATION_DATE);
  const PLAIN_TEXT = stringToByteArray(PRODUCT_CODE);
  const AES_KEY = CryptoJS.enc.Hex.parse(config.AES_KEY);
  const rc4 = new RC4(uid);
  const data = rc4.encrypt(PLAIN_TEXT);
  let dataHex = '';
  data.forEach((item) => (dataHex += item.toString(16).toUpperCase().padStart(2, '0')));
  const iv = CryptoJS.lib.WordArray.create(new ArrayBuffer(16));
  const ciphertext = CryptoJS.AES.encrypt(CryptoJS.enc.Hex.parse(dataHex), AES_KEY, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  const HexData = CryptoJS.enc.Utf8.parse(ciphertext.toString()).toString(CryptoJS.enc.Hex).toUpperCase();

  // console.log("encode data", HexData, ciphertext.toString());
  return {
    data: HexData,
    text: ciphertext.toString(),
  };
}
export function stringToByteArray(str) {
  const byteArray = new Uint8Array(str.length);
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    const hexString = charCode.toString(16).padStart(2, '0');
    const byteValue = parseInt(hexString, 16);
    byteArray[i] = byteValue;
  }
  return byteArray;
}
class RC4 {
  constructor(key) {
    this.key = key;
    this.s = new Uint8Array(256);

    this.initializeS();
  }

  swap(arr, i, j) {
    const tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
  }

  initializeS() {
    const t = new Uint8Array(256);
    for (let i = 0; i < 256; i++) {
      this.s[i] = i;
      t[i] = this.key[i % this.key.length];
    }
    let j = 0;
    for (let i = 0; i < 256; i++) {
      j = (j + this.s[i] + t[i]) & 0xff;
      this.swap(this.s, i, j);
    }
  }

  encrypt(plaintext) {
    const cipherText = new Uint8Array(plaintext.length);
    let i = 0;
    let j = 0;
    let k;
    let t;
    for (let counter = 0; counter < plaintext.length; counter++) {
      i = (i + 1) & 0xff;
      j = (j + this.s[i]) & 0xff;
      this.swap(this.s, i, j);
      t = (this.s[i] + this.s[j]) & 0xff;
      k = this.s[t];
      cipherText[counter] = plaintext[counter] ^ k;
    }
    return cipherText;
  }
}
